import {BaseDatabase} from './base'
import {AESEncryptor} from "./encryptors/aes.ts";

export interface HistoryItem {
  id: string
  path: string
  timestamp: number
  type: 'file' | 'directory'
  action: 'open' | 'create' | 'modify' | 'delete'
}

export class HistoryDatabase extends BaseDatabase {
  private maxItems: number = 1000

  constructor() {
    super('history', undefined, {
      encryptor: new AESEncryptor({
        key: '61008085554a456b8f0242b72f6dc060'
      })
    })
  }

  addHistory(item: Omit<HistoryItem, 'id' | 'timestamp'>): void {
    const historyItem: HistoryItem = {
      ...item,
      id: this.generateId(),
      timestamp: Date.now()
    }

    this.db.insert(this.getPath([]), historyItem)
    this.cleanup()
  }

  getHistory(limit: number = 50, offset: number = 0): HistoryItem[] {
    return this.db.query(this.getPath([]))
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(offset, offset + limit)
  }

  searchHistory(query: string): HistoryItem[] {
    return this.db.query(this.getPath([]))
      .filter(item => item.path.toLowerCase().includes(query.toLowerCase()))
      .sort((a, b) => b.timestamp - a.timestamp)
  }

  clearHistory(): void {
    this.db.update(this.getPath([]), [])
  }

  private cleanup(): void {
    const items = this.db.query(this.getPath([]))
    if (items.length > this.maxItems) {
      const sortedItems = items.sort((a, b) => b.timestamp - a.timestamp)
      const keepItems = sortedItems.slice(0, this.maxItems)
      this.db.update(this.getPath([]), keepItems)
    }
  }

  private generateId(): string {
    return Math.random().toString(36).substring(2) + Date.now().toString(36)
  }
}
